<?php

namespace App\Http\Middleware;
use \App\User;
use Closure;
use Api;

class ApiValideMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    
    public function handle($request, Closure $next)
    {
        $email = $request->input('email');
        $api_token = $request->input('api_token');
        $user = User::where('email',$email)->first();
        if($user !== null)
        {
            if($user->api_token === $api_token)
            {
                if(Api::isHeartbeatExpired($user) === false)
                {
                    return $next($request);
                }
                else
                {
                    Api::addError(4);
                    $user->api_token = null;
                    $user->save();
                }
            }
            else
            {
                Api::addError(2);
            }
        }
        else
        {
            Api::addError(1);
        }
        Api::setState(2);
        return new \Illuminate\Http\Response(null);      

    }
}
